﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; // For Encoding
using System.Net.Sockets; // For TcpClient, NetworkStream, SocketException
using System.Threading;


namespace csharp
{
    class console
    {
        static int outCol, outRow, outHeight = 10;

        static void Main()
        {
            Thread t = new Thread(WriteY);          // Kick off a new thread
            t.Start();                               // running WriteY()
            string ble = "";
            string nick = "<Valdi>";
            while (true) {
                ble = Console.ReadLine();
                nick += " ";
                nick += ble;
                WriteOut(nick, true);
                nick = "<Valdi>";
            }
        }

        static void WriteY()
        {

            for (int i = 0; i < 10000; i++)
            {
                WriteOut("Server: haha", true);
                Thread.Sleep(3000);
            }
            
        }
        static void WriteOut(string msg, bool appendNewLine)
        {
            int inCol, inRow;
            inCol = Console.CursorLeft;
            inRow = Console.CursorTop;
            outHeight++;
            Console.BufferHeight++;
            msg += Console.BufferHeight;

            int outLines = getMsgRowCount(outCol, msg) + (appendNewLine ? 1 : 0);
            int outBottom = outRow + outLines;
            if (outBottom > outHeight)
                outBottom = outHeight;
            if (inRow <= outBottom)
            {
                int scrollCount = outBottom - inRow + 1;
                Console.MoveBufferArea(0, inRow, Console.BufferWidth, 1, 0, inRow + scrollCount);
                inRow += scrollCount;
            }
            if (outRow + outLines > outHeight)
            {
                int scrollCount = outRow + outLines - outHeight;
                Console.MoveBufferArea(0, scrollCount, Console.BufferWidth, outHeight - scrollCount, 0, 0);
                outRow -= scrollCount;
                Console.SetCursorPosition(outCol, outRow);
            }
            Console.SetCursorPosition(outCol, outRow);
            if (appendNewLine)
                Console.WriteLine(msg);
            else
                Console.Write(msg);
            outCol = Console.CursorLeft;
            outRow = Console.CursorTop;
            Console.SetCursorPosition(inCol, inRow);
        }

        static int getMsgRowCount(int startCol, string msg)
        {
            string[] lines = msg.Split('\n');
            int result = 0;
            foreach (string line in lines)
            {
                result += (startCol + line.Length) / Console.BufferWidth;
                startCol = 0;
            }
            return result + lines.Length - 2;
        }
    }
}
